package com.example.blog.modules.system.controller;

import com.example.blog.common.api.ApiResponse;
import com.example.blog.common.security.HasPermission;
import com.example.blog.modules.system.service.CacheWarmUpService;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.stats.CacheStats;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Tag(name = "缓存管理", description = "缓存管理相关接口")
@RestController
@RequestMapping("/api/cache")
@RequiredArgsConstructor
public class CacheController {

    private final CacheManager cacheManager;
    private final CacheWarmUpService cacheWarmUpService;

    @Operation(summary = "清理指定缓存")
    @DeleteMapping("/{cacheName}")
    @HasPermission("cache:clear")
    public ApiResponse<Void> clearCache(@PathVariable String cacheName) {
        org.springframework.cache.Cache cache = cacheManager.getCache(cacheName);
        if (cache != null) {
            cache.clear();
            return ApiResponse.success();
        }
        return ApiResponse.error("缓存不存在");
    }

    @Operation(summary = "清理所有缓存")
    @DeleteMapping
    @HasPermission("cache:clear")
    public ApiResponse<Void> clearAllCaches() {
        cacheManager.getCacheNames().forEach(name -> {
            org.springframework.cache.Cache cache = cacheManager.getCache(name);
            if (cache != null) {
                cache.clear();
            }
        });
        return ApiResponse.success();
    }

    @Operation(summary = "获取缓存统计信息")
    @GetMapping("/stats")
    @HasPermission("cache:view")
    public ApiResponse<Map<String, Object>> getCacheStats() {
        Map<String, Object> stats = new HashMap<>();
        
        cacheManager.getCacheNames().forEach(name -> {
            org.springframework.cache.Cache springCache = cacheManager.getCache(name);
            if (springCache instanceof CaffeineCache caffeineCache) {
                Cache<Object, Object> nativeCache = caffeineCache.getNativeCache();
                CacheStats cacheStats = nativeCache.stats();
                
                Map<String, Object> cacheInfo = new HashMap<>();
                cacheInfo.put("hitCount", cacheStats.hitCount());
                cacheInfo.put("missCount", cacheStats.missCount());
                cacheInfo.put("hitRate", cacheStats.hitRate());
                cacheInfo.put("missRate", cacheStats.missRate());
                cacheInfo.put("evictionCount", cacheStats.evictionCount());
                cacheInfo.put("estimatedSize", nativeCache.estimatedSize());
                
                stats.put(name, cacheInfo);
            }
        });
        
        return ApiResponse.success(stats);
    }

    @Operation(summary = "预热缓存")
    @PostMapping("/{cacheName}/warm-up")
    @HasPermission("cache:manage")
    public ApiResponse<Void> warmUpCache(@PathVariable String cacheName) {
        try {
            cacheWarmUpService.warmUpCache(cacheName);
            return ApiResponse.success();
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
} 